package com.ficus.road.maintain.file;

import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;

/**
 * @author xiawen yang
 * @date 2022/6/20 下午3:35
 */
@Slf4j
public class OSSFileClient extends AbstractFileClient<OSSClientConfig> {

    private OSSClient ossClient;

    public OSSFileClient(String clientName, OSSClientConfig config) {
        super(clientName, config);
    }

    @Override
    protected void doInit() {
        ossClient = new OSSClient(config.getEndpoint(),
                new DefaultCredentialProvider(config.getAccessKeyId(), config.getAccessKeySecret()),
                new ClientConfiguration());
    }

//    @Override
//    public UploadResult upload(byte[] content, String path) throws Exception {
//        InputStream inputStream = new ByteArrayInputStream(content);
//        //上传文件
//        UploadResult uploadResult = upload0(inputStream, "png", path);
//        if (uploadResult.getCode() != 200) {
//            log.error("upload0 failed");
//            // 如果失敗，重試一次
//            uploadResult = upload0(inputStream, "png", path);
//        }
//        return uploadResult;
//    }

    @Override
    protected UploadResult upload0(InputStream inputStream, String path, String contentType) {
        UploadResult uploadResult;

        //初始化客户端
        try {
            // 创建上传Object的Metadata
            ObjectMetadata meta = new ObjectMetadata();
            // 设置上传内容类型
            meta.setContentType(contentType);
            //被下载时网页的缓存行为
            meta.setCacheControl("no-cache");
            //创建上传请求
            PutObjectRequest request = new PutObjectRequest(config.getBucketName(), path, inputStream, meta);
            //上传文件
            ossClient.putObject(request);

            String url = getUrl(path);
            //获取上传成功的文件地址
            uploadResult = new UploadResult(url, path, 200);
        } catch (Exception e) {
            log.error("oss upload file met exception:", e);
            uploadResult = new UploadResult(null, null, 400);
            return uploadResult;
        }
        return uploadResult;
    }

    @Override
    public void uploadDirect(byte[] content, String path) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(config.getBucketName(), path, new ByteArrayInputStream(content));
        ossClient.putObject(putObjectRequest);
    }

    @Override
    public OSSObject getContent(String path) {
        return ossClient.getObject(config.getBucketName(), path);
    }

    @Override
    public Object getContentByUrl(String url) {
        String str = OSSClientConfig.urlPrefix;
        int beginIndex = url.indexOf(str);
        if (beginIndex == -1)
            return null;
        String path = url.substring(beginIndex + str.length());
        return getContent(path);
    }

    @Override
    public String getUrl(String path) throws Exception {
        Date expiration = new Date(new Date().getTime() + OSSClientConfig.FILE_EXPIRATION_TIME);// 生成URL
        GeneratePresignedUrlRequest generatePresignedUrlRequest;
        generatePresignedUrlRequest = new GeneratePresignedUrlRequest(config.getBucketName(), path);
        generatePresignedUrlRequest.setExpiration(expiration);
        URL url = ossClient.generatePresignedUrl(generatePresignedUrlRequest);
        String[] split = url.toString().split("\\?");
        return split[0].replace("-internal", "");
    }
}
